<template>
  <div class="users-container">
    <!-- 统计卡片 -->
    <el-row :gutter="20" class="dashboard-cards">
      <el-col :span="8">
        <el-card shadow="hover" class="dashboard-card">
          <div class="card-content">
            <i class="el-icon-user"></i>
            <div class="card-info">
              <div class="card-title">总用户数</div>
              <div class="card-number">{{ pagination.total }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card shadow="hover" class="dashboard-card">
          <div class="card-content">
            <i class="el-icon-s-custom"></i>
            <div class="card-info">
              <div class="card-title">管理员数</div>
              <div class="card-number">{{ adminCount }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card shadow="hover" class="dashboard-card">
          <div class="card-content">
            <i class="el-icon-s-tools"></i>
            <div class="card-info">
              <div class="card-title">普通用户数</div>
              <div class="card-number">{{ normalUserCount }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form" size="small">
        <el-form-item label="用户名">
          <el-input v-model="searchForm.username" placeholder="请输入用户名" prefix-icon="el-icon-search"></el-input>
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="searchForm.role" placeholder="请选择角色" clearable>
            <el-option label="管理员" :value="1"></el-option>
            <el-option label="普通用户" :value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button-group>
            <el-button type="primary" icon="el-icon-search" @click="handleSearch">查询</el-button>
            <el-button icon="el-icon-refresh" @click="resetSearch">重置</el-button>
            <el-button type="success" icon="el-icon-plus" @click="handleAdd">新增用户</el-button>
          </el-button-group>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card">
      <el-table
        :data="tableData"
        border
        stripe
        style="width: 100%"
        v-loading="loading"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="id" label="ID" width="80" sortable></el-table-column>
        <el-table-column prop="username" label="用户名" width="180"></el-table-column>
        <el-table-column label="角色" width="120">
          <template slot-scope="scope">
            <el-tag :type="scope.row.role === '1' ? 'danger' : 'success'" effect="dark">
              {{ scope.row.role === '1' ? '管理员' : '普通用户' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template slot-scope="scope">
            <el-button-group>
              <el-button
                size="mini"
                type="primary"
                icon="el-icon-edit"
                @click="handleEdit(scope.row)">
                编辑
              </el-button>
              <el-button
                size="mini"
                type="danger"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                :disabled="scope.row.role === '1'">
                删除
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <!-- 批量操作工具栏 -->
      <div class="batch-operation-bar" v-show="selectedUsers.length > 0">
        <span class="selected-count">已选择 {{ selectedUsers.length }} 项</span>
        <el-button-group>
          <el-button size="mini" type="danger" @click="batchDelete">批量删除</el-button>
        </el-button-group>
      </div>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagination.currentPage"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="pagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          background>
        </el-pagination>
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="40%"
      :close-on-click-modal="false"
      :destroy-on-close="true">
      <el-form :model="form" :rules="rules" ref="form" label-width="100px" size="small">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" :disabled="form.id"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="!form.id">
          <el-input v-model="form.password" type="password" show-password></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword" v-if="!form.id">
          <el-input v-model="form.confirmPassword" type="password" show-password></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="form.role" placeholder="请选择角色">
            <el-option label="管理员" :value="'1'"></el-option>
            <el-option label="普通用户" :value="'2'"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Users',
  data() {
    const validatePass2 = (rule, value, callback) => {
      if (value !== this.form.password) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    return {
      searchForm: {
        username: '',
        role: ''
      },
      tableData: [],
      loading: false,
      selectedUsers: [],
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },
      dialogVisible: false,
      dialogTitle: '新增用户',
      form: {
        username: '',
        password: '',
        confirmPassword: '',
        role: '2'
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '请再次输入密码', trigger: 'blur' },
          { validator: validatePass2, trigger: 'blur' }
        ],
        role: [
          { required: true, message: '请选择角色', trigger: 'change' }
        ]
      }
    }
  },
  computed: {
    // 管理员数量
    adminCount() {
      return this.tableData.filter(user => user.role === '1').length
    },
    // 普通用户数量
    normalUserCount() {
      return this.tableData.filter(user => user.role === '2').length
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    // 获取数据
    async fetchData() {
      this.loading = true
      try {
        const params = {
          page: this.pagination.currentPage,
          size: this.pagination.pageSize,
          username: this.searchForm.username,
          role: this.searchForm.role
        }
        const res = await this.$axios.get('/user/list', { params })
        this.tableData = res.data.records
        this.pagination.total = res.data.total
      } catch (error) {
        this.$message.error('获取数据失败')
      } finally {
        this.loading = false
      }
    },
    // 表格选择
    handleSelectionChange(val) {
      this.selectedUsers = val
    },
    // 批量删除
    async batchDelete() {
      if (!this.selectedUsers.length) {
        this.$message.warning('请选择要删除的用户')
        return
      }
      try {
        await this.$confirm(`确认删除选中的 ${this.selectedUsers.length} 个用户吗？`, '提示', {
          type: 'warning'
        })
        await this.$axios.post('/user/batch-delete', {
          userIds: this.selectedUsers.map(user => user.id)
        })
        this.$message.success('批量删除成功')
        this.fetchData()
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('批量删除失败')
        }
      }
    },
    // 搜索
    handleSearch() {
      this.pagination.currentPage = 1
      this.fetchData()
    },
    // 重置搜索
    resetSearch() {
      this.searchForm = {
        username: '',
        role: ''
      }
      this.handleSearch()
    },
    // 新增
    handleAdd() {
      this.dialogTitle = '新增用户'
      this.form = {
        username: '',
        password: '',
        confirmPassword: '',
        role: '2'
      }
      this.dialogVisible = true
    },
    // 编辑
    handleEdit(row) {
      this.dialogTitle = '编辑用户'
      this.form = {
        id: row.id,
        username: row.username,
        role: row.role
      }
      this.dialogVisible = true
    },
    // 删除
    handleDelete(row) {
      this.$confirm('确认删除该用户吗？', '提示', {
        type: 'warning'
      }).then(async () => {
        try {
          await this.$axios.delete(`/user/delete/${row.id}`)
          this.$message.success('删除成功')
          this.fetchData()
        } catch (error) {
          this.$message.error('删除失败')
        }
      }).catch(() => {})
    },
    // 提交表单
    handleSubmit() {
      this.$refs.form.validate(async valid => {
        if (valid) {
          try {
            if (this.form.id) {
              // 编辑
              await this.$axios.put('/user/update', {
                id: this.form.id,
                username: this.form.username,
                role: this.form.role
              })
              this.$message.success('更新成功')
            } else {
              // 新增
              await this.$axios.post('/user/add', {
                username: this.form.username,
                password: this.form.password,
                role: this.form.role
              })
              this.$message.success('添加成功')
            }
            this.dialogVisible = false
            this.fetchData()
          } catch (error) {
            this.$message.error(error.message || '操作失败')
          }
        }
      })
    },
    // 分页
    handleSizeChange(val) {
      this.pagination.pageSize = val
      this.fetchData()
    },
    handleCurrentChange(val) {
      this.pagination.currentPage = val
      this.fetchData()
    }
  }
}
</script>

<style scoped>
.users-container {
  padding: 20px;
  background-color: #f0f2f5;
  min-height: calc(100vh - 84px);
}

.dashboard-cards {
  margin-bottom: 20px;
}

.dashboard-card {
  cursor: pointer;
  transition: all 0.3s;
}

.dashboard-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
}

.card-content {
  display: flex;
  align-items: center;
}

.card-content i {
  font-size: 48px;
  color: #409EFF;
  margin-right: 20px;
}

.card-info {
  flex: 1;
}

.card-title {
  font-size: 14px;
  color: #909399;
}

.card-number {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  margin-top: 5px;
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  padding: 10px 0;
}

.table-card {
  margin-bottom: 20px;
}

.batch-operation-bar {
  margin: 10px 0;
  padding: 10px;
  background-color: #ecf5ff;
  border-radius: 4px;
}

.selected-count {
  margin-right: 20px;
  color: #409EFF;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

/* 添加响应式样式 */
@media screen and (max-width: 1200px) {
  .el-form-item {
    margin-bottom: 10px;
  }
  
  .dashboard-cards .el-col {
    margin-bottom: 20px;
  }
}
</style> 